#include "ComputeEdgeGradient.h"

#include "../DWMRICore/Fiber.h"
#include "../DWMRICore/Scalar.h"
#include "../DWMRICore/VectorField.h"

#include <omp.h>

enum ES_METHOD{
	ES_NONE,
	ES_FTLE,		/* FTLE */
	ES_PP,			/* Point Pair */
	ES_NEW			/* New method, compute graident based on estimated function */
};

char *fiber_pathname = NULL;
char *dst_pathname = NULL;
ES_METHOD method = ES_NONE;

char **confPathname = NULL;
char **vertPathname = NULL;
int w, h, d, scale;
float stepSize, maxLength;

float fiber_length = 0.0f;

void PrintUsage()
{
	printf("Usage: ComputeEdgeGradient -fiber <configure_file> -dst <dst_file> -method <method> -length <fiber_length>\n");
}

int ParseArguments(const int argc, char *argv[])
{
	for (int i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "-fiber") == 0) {
			fiber_pathname = argv[++i];
		} else if (strcmp(argv[i], "-dst") == 0) {
			dst_pathname = argv[++i];
		} else if (strcmp(argv[i], "-length") == 0) {
			fiber_length = (float)atof(argv[++i]);
		} else if (strcmp(argv[i], "-method") == 0) {
            i++;
			if (strcmp(argv[i], "FTLE") == 0 || strcmp(argv[i], "ftle") == 0) {
				method = ES_FTLE;
			} else if (strcmp(argv[i], "PP") == 0 || strcmp(argv[i], "pp") == 0) {
				method = ES_PP;
			} else if (strcmp(argv[i], "NEW") == 0 || strcmp(argv[i], "new") == 0) {
				method = ES_NEW;
			} else {
				return -1;
			}
		} else {
			return -1;
		}
	}

	if (fiber_pathname == NULL || dst_pathname == NULL || method == ES_NONE || fiber_length < 0.0f)
		return -2;

	return 0;
}

void ComputeEdgeGradientByFTLE(CVector3F *edgeGradient)
{
	CFiber *fibers[3];
	int cw, ch;
	
    int offset[9];
    offset[ 0] = 0;
    offset[ 1] = -1;
    offset[ 2] = 1;
    offset[ 3] = -w-1;
    offset[ 4] = -w;
    offset[ 5] = -w+1;
    offset[ 6] = w-1;
    offset[ 7] = w;
    offset[ 8] = w+1;
	
    omp_set_num_threads(64);

	float length = fiber_length > maxLength ? maxLength : fiber_length;
	int id = length / stepSize;
	float delta = 1.0f / (float)scale;

	for (int z = 1; z < d - 1; ++z) {
		ReadFibers(confPathname[z-1], vertPathname[z-1], &(fibers[0]), cw, ch);
		ReadFibers(confPathname[z+0], vertPathname[z+0], &(fibers[1]), cw, ch);
		ReadFibers(confPathname[z+1], vertPathname[z+1], &(fibers[2]), cw, ch);
		
		
		for (int y = 1; y < h - 1; ++y) {
#pragma omp parallel for            
            for (int x = 1; x < w - 1; ++x) {
				int index = y * w + x;
				CFiber *f[27];

				f[0] = &(fibers[1][index]);			// fiber of current voxel

				for (int i = 1; i < 9; ++i) {
					f[i] = &(fibers[1][index+offset[i]]);
				}
				for (int i = 0; i < 9; ++i) {
					f[i+9] = &(fibers[0][index+offset[i]]);
				}
				for (int i = 0; i < 9; ++i) {
					f[i+18] = &(fibers[2][index+offset[i]]);
				}
			
				edgeGradient[z*w*h+index] = EdgeGradientMethodFTLE(f, id, delta);
			}
		}

		delete[] fibers[0];
		delete[] fibers[1];
		delete[] fibers[2];

		printf("z = %d\n", z);
	}
	
	
}

void ComputeEdgeGradientByNewMethod(CVector3F *edgeGradient)
{
    int offset[9];
    offset[ 0] = 0;
    offset[ 1] = -1;
    offset[ 2] = 1;
    offset[ 3] = -w-1;
    offset[ 4] = -w;
    offset[ 5] = -w+1;
    offset[ 6] = w-1;
    offset[ 7] = w;
    offset[ 8] = w+1;
    
    omp_set_num_threads(16);

	float length = fiber_length > maxLength ? maxLength : fiber_length;
	int stepSize = int((length * RESAMPLE) / ((PARAM_COUNT-1) / 2));

	for (int z = 1; z < d - 1; ++z) {
        CFiber **fibers[3];
        int *count[3];
        int cw, ch;
        
        ReadFibers(confPathname[z-1], vertPathname[z-1], &(fibers[0]), &(count[0]), cw, ch);
        ReadFibers(confPathname[z+0], vertPathname[z+0], &(fibers[1]), &(count[1]), cw, ch);
		ReadFibers(confPathname[z+1], vertPathname[z+1], &(fibers[2]), &(count[2]), cw, ch);
		
		for (int y = 1; y < h-1; ++y) {
#pragma omp parallel for            
			for (int x = 1; x < w-1; ++x) {
				int index = y * w + x;

                for (int k = 0; k < count[1][index]; ++k) {

                    CFiber *f[27];
                    f[0] = &(fibers[1][index][k]);
                    CVector3F dir = f[0]->m_seed.dir;

                    int id = 1;
					bool flag = true;
					for (int l = 0; l < 3; ++l) {
						for (int i = 0; i < 9; ++i) {
							if (l == 1 && i == 0)
								continue;
							float max_v = -1.0f;
							int max_index;
							int temp_index = index + offset[i];
							int size = count[l][temp_index];
							for (int j = 0; j < size; ++j) {
								float v = InnerProduct(dir, fibers[l][temp_index][j].m_seed.dir);
								if (fabs(v) > max_v) {
									max_v = fabs(v);
									max_index = j;
									if (l == 0) {
										f[9+i] = &(fibers[l][temp_index][j]);
									} else if (l == 1) {
										f[i] = &(fibers[l][temp_index][j]);
									} else {
										f[18+i] = &(fibers[l][temp_index][j]);
									}
								}                            
							}
						}
					}

					edgeGradient[z*w*h+index] = EdgeGradientMethodNEW(f, 27, stepSize);
                }
			}
		}

        for (int i = 0; i < w * h; ++i) {
            SafeDeleteArray(fibers[0][i]);
            SafeDeleteArray(fibers[1][i]);
            SafeDeleteArray(fibers[2][i]);
        }
	    SafeDeleteArray(fibers[0]);
        SafeDeleteArray(fibers[1]);
        SafeDeleteArray(fibers[2]);	
	    SafeDeleteArray(count[0]);
        SafeDeleteArray(count[1]);
        SafeDeleteArray(count[2]);	

        printf("z = %d\n", z);
        fflush(stdout);
	}
}


int main(int argc, char *argv[])
{
    //test();

	if (ParseArguments(argc, argv) != 0) {
		PrintUsage();
		return 0;
	}
	
	/* read the configure file */
	ReadConfigureFile(fiber_pathname, &confPathname, &vertPathname, w, h, d, scale, stepSize, maxLength);
	
	/* compute edge gradient for each voxel */
	CVector3F *edgeGradient = new CVector3F[w*h*d];
	memset(edgeGradient, 0, sizeof(CVector3F)*w*h*d);
	
	if (method == ES_FTLE) {
		ComputeEdgeGradientByFTLE(edgeGradient);
	} else if (method == ES_PP) {
		//ComputeEdgeGradientByPointPair(edgeStrength);
	} else if (method == ES_NEW) {
		ComputeEdgeGradientByNewMethod(edgeGradient);
	} else {
		;
	}

    /* save the result */
    CVectorField *result = new CVectorField();
	result->CreateVectorField(w, h, d);
	for (int i = 0; i < w * h * d; ++i) {
		result->SetVector(i, edgeGradient[i]);
	}
	result->SaveVectorFieldFile(dst_pathname);

    delete result;
	
	for (int z = 0; z < d; ++z) {
		delete[] confPathname[z];
		delete[] vertPathname[z];
	}
	delete[] confPathname;
	delete[] vertPathname;
	
	delete[] edgeGradient;
}
